﻿using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.Linq;

using System.Web.UI.DataVisualization.Charting;
using System.Globalization;
using CommunergyLogic;
using Communergy.Repository;
using Communergy.Repository.EntityFramework;

public partial class _Default : System.Web.UI.Page
{
    Guid userGuid;
    protected void Page_Load(object sender, EventArgs e)
    {
        MembershipUser thisUser = Membership.GetUser();
        communergyEntities db = new communergyEntities();
        if (!Page.IsPostBack && thisUser != null)
        {

            // CommunergySQLDataContext db = new CommunergySQLDataContext();
            //var userMeters = db.ElectricityMeters.Where(m => m.me_aspUserId == (Guid)thisUser.ProviderUserKey);

            userGuid = new Guid(thisUser.ProviderUserKey.ToString());
            
            //var userMeters = db.ElectricityMeter.Where(m => m.me_aspUserId == userGuid);

            var userMeters = from m in db.ElectricityMeter.Where(em => em.me_aspUserId == userGuid)
                             join ed in db.ElectricityDaily_Manual
                                    on m equals ed.ElectricityMeter into meterInfo
                             from mi in meterInfo
                             group mi.de_kWhDaily by
                             new
                             {
                                 m.me_id,
                                 m.me_meterName,
                                 StartDate = meterInfo.Min(em => em.de_dateTime),
                                 EndDate = meterInfo.Max(em => em.de_dateTime)
                             }
                                 into meterTotals

                                 select new
                                     {
                                         MeterId = meterTotals.Key.me_id,
                                         StartDate = meterTotals.Key.StartDate,
                                         EndDate = meterTotals.Key.EndDate,
                                         MeterName = meterTotals.Key.me_meterName,
                                         Days = meterTotals.Count(),
                                         TotalKWh = meterTotals.Sum(),
                                         Average = meterTotals.Average()
                                     };



            var lstUserMeters = LoginView1.FindControl("lstUserMeters") as GridView;
            if (lstUserMeters != null)
            {
                lstUserMeters.DataSource = userMeters;
                lstUserMeters.DataBind();
            }

           
        }

        var lastReading = db.ElectricityDaily_Manual.OrderByDescending(de => de.de_dateTime).FirstOrDefault();

        int daysHistory = -14;
        var last7Days = lastReading.de_dateTime.AddDays(daysHistory);

        var recentMinMax = from ed in db.ElectricityDaily_Manual
                           where ed.de_dateTime > last7Days
                           group ed.de_kWhDaily by ed.de_dateTime into daily
                           orderby daily.Key
                           select new
                           {
                               Day = daily.Key,
                               Max = daily.Max(),
                               Min = daily.Min()
                           };
        var dates = (from m in recentMinMax select m.Day).ToArray();
        var max =( from m in recentMinMax select m.Max.Value).ToArray();
        var min = (from m in recentMinMax select m.Min).ToArray();

        string titleText = string.Format("Energy use ranges for all public meters, {0} to {1}", last7Days.ToShortDateString(), lastReading.de_dateTime.ToShortDateString());


        chartRange.Titles[0].Text = titleText;
        chartRange.Series["Default"].Points.DataBindXY(dates, min, max);
        var minDate = new DateTime(1900, 1, 1).AddDays(-2);
        foreach (var item in chartRange.Series["Default"].Points)
        {
            Console.WriteLine(item.YValues.ToString());
            string toolTip = string.Format("{0}, {1}kWh - {2}kWh", minDate.AddDays( item.XValue).ToShortDateString(), item.YValues[0], item.YValues[1]);
            item.ToolTip = toolTip;
        }

        if (thisUser != null)
        {
            var legendName = "UserLegend";
            chartRange.Legends.Add(new Legend(legendName));
            var meters = db.ElectricityMeter.Include("ElectricityDaily_Manual").Where(m => m.me_aspUserId == userGuid);
            foreach (var meter in meters)
            {
                string userTitle = string.Format("Meter readings for {0} displayed as lines within ranges", thisUser.UserName);
                chartRange.Titles["userTitle"].Text = userTitle;
                chartRange.Titles["userTitle"].Visible = true;

                var meterReadings = from mr in meter.ElectricityDaily_Manual
                                    orderby mr.de_dateTime
                                    where mr.de_dateTime > last7Days
                                    select new { mr.de_dateTime, mr.de_kWhDaily };
                var seriesName = meter.me_meterName;
                Series series = chartRange.Series.Add(seriesName);

                series.Legend = legendName;
                foreach (var reading in meterReadings)
                {
                    var convertedReading = Convert.ToDouble(reading.de_kWhDaily.Value);
                    series.Points.AddXY(reading.de_dateTime, convertedReading);
                }
                
                series.ChartArea = "ChartArea1";
                series.ChartType = SeriesChartType.Line;
                series.BorderWidth = 2; 
            }

            this.chartRange.Legends[legendName].IsDockedInsideChartArea = true;
            this.chartRange.Legends[legendName].DockedToChartArea = "ChartArea1";
            //System.Data.Linq.SqlClient.SqlMethods.DateDiffMinute
            
        }
        
     
    }


    protected void ListView1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
}
